package com.coderknock.bbs.conf

import com.coderknock.bbs.web.response.Response
import org.apache.commons.logging.LogFactory
import org.springframework.validation.BindException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody

/**
 * <p>全局捕获</p>
 * @author 三产
 * @version 1.0
 * @date 2017-11-29
 * @QQGroup 213732117
 * @website http://www.coderknock.com
 * @copyright Copyright 2017 拿客 coderknock.com  All rights reserved.
 * @since JDK 1.8
 */
@ControllerAdvice
class GlobalDefaultExceptionHandler {
    private val logger = LogFactory.getLog(GlobalDefaultExceptionHandler::class.java)


    @ExceptionHandler(value = Exception::class)
    @ResponseBody
    fun defaultErrorHandler(ex: Exception): Response<*> {
        val resultJson = Response<Boolean>(data = false)
        if (ex is BindException) {
            val result = ex.bindingResult
            if (result != null && result.hasErrors()) {
                val list = result.allErrors
                list.forEach { objectError -> resultJson.msg += objectError.defaultMessage }
            }
        }
        logger.error("异常:" + ex.message, ex)
        return resultJson
    }
}